//
//  LWHomeViewController.m
//  IOSResume
//
//  Created by wynn on 16/4/19.
//  Copyright © 2016年 wynn. All rights reserved.
//

#import "LWHomeViewController.h"
#import "SubLBXScanViewController.h"
#import "HYAwesomeTransition.h"
#import "LWLoginViewController.h"
#import "LWResumeViewController.h"

@interface LWHomeViewController ()<UIViewControllerTransitioningDelegate,LWResumeViewControllerDelegate,UINavigationControllerDelegate>
{
    CAShapeLayer *progressLayer;
    CGFloat tabbarHeight;
    CGFloat topMargin;
    BOOL emailAtServerBool;
    BOOL validEmailAtServerHaveResumeBool;
}

@property (nonatomic, strong) UIButton *loginButton; // 登陆按钮
@property (nonatomic, strong) UIButton *moreButton; // 更多按钮
@property (nonatomic, strong) UIButton *queryButton; // 查询按钮
@property (nonatomic, strong) UIImage *defaultHeadImage; // 默认头像图片
@property (nonatomic, strong) UIImageView *headImageView; // 显示头像
@property (nonatomic, strong) UILabel *tipLabel; // 轻度提示词
@property (nonatomic, strong) UITextField *emailTextField; // 邮箱输入框
@property (nonatomic, strong) BmobUser *user; // Bmob用户
@property (nonatomic, strong) HYAwesomeTransition *awesometransition; // 头像进入到下一个界面的动画
@property (nonatomic, strong) SubLBXScanViewController *scanViewController;

@end

@implementation LWHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // 处理shortCutItem 通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoTestVc:) name:@"gotoTestVc" object:nil];
    
    // 创建背景图片
    if (!_headImageView) {
        self.view.backgroundColor = MILK_WHITE;
        
        tabbarHeight = 64;
        topMargin = 100.0 + tabbarHeight;
        startMargin = 50.0;
        emailAtServerBool = NO;
        validEmailAtServerHaveResumeBool = NO;
        self.defaultHeadImage = [UIImage imageNamed:@"defaultHead"];
        
        // 扫描二维码按钮
        UIImage *scanImage = [UIImage imageNamed:@"scan"];
        UIImageView *scanImageView = [[UIImageView alloc] initWithImage:scanImage];
        scanImageView.frame = CGRectMake(startMargin, startMargin, startMargin, startMargin);
        [scanImageView setUserInteractionEnabled:YES];
        [scanImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scanQRCode)]];
        [self.view addSubview:scanImageView];
        // 默认头像
        self.headImageView = [[UIImageView alloc] initWithImage:self.defaultHeadImage];
        self.headImageView.frame = CGRectMake((SCREEN.width - 100) * 0.5, topMargin, 100, 100);
        self.headImageView.layer.cornerRadius = 50;
        self.headImageView.layer.masksToBounds = YES;
        self.headImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.headImageView setUserInteractionEnabled:YES];
        [self.headImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showResumeWithTap:)]];
        [self.view addSubview:self.headImageView];
        // 邮箱地址
        self.emailTextField = [[UITextField alloc] init];
        self.emailTextField.frame = CGRectMake(startMargin, CGRectGetMaxY(_headImageView.frame)+startMargin, SCREEN.width - 100.0, 40.0);
        self.emailTextField.placeholder = @"邮箱";
        self.emailTextField.textColor = [UIColor blackColor];
        [self.emailTextField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
        [self.view addSubview:self.emailTextField];
        self.emailTextField.layer.borderColor = MILK_GRAY.CGColor;
        self.emailTextField.layer.borderWidth = 1.0;
        self.emailTextField.layer.cornerRadius = 20.0;
        self.emailTextField.textAlignment = NSTextAlignmentCenter;
        // 查询按钮
        self.queryButton = [UIButton buttonWithType:UIButtonTypeCustom];
        self.queryButton.frame = CGRectMake(startMargin, CGRectGetMaxY(self.headImageView.frame)+startMargin*2, SCREEN.width - 100.0, 40.0);
        [self.queryButton setTitle:@"查询" forState:UIControlStateNormal];
        [self.queryButton setTitleColor:MILK_WHITE forState:UIControlStateNormal];
        [self.queryButton setTitleColor:MILK_GRAY forState:UIControlStateHighlighted];
        [self.view addSubview:self.queryButton];
        [self.queryButton setBackgroundColor:MILK_RED];
        self.queryButton.layer.cornerRadius = 20.0;
        [self.queryButton addTarget:self action:@selector(queryClick:) forControlEvents:UIControlEventTouchUpInside];
        // 提示文字
        self.tipLabel = [[UILabel alloc] init];
        self.tipLabel.frame = CGRectMake(startMargin, CGRectGetMaxY(self.headImageView.frame)+startMargin*3, SCREEN.width - 100.0, 80.0);
        [self.view addSubview:self.tipLabel];
        self.tipLabel.textColor = MILK_RED;
        self.tipLabel.textAlignment = NSTextAlignmentCenter;
        // 头像动画
        self.awesometransition = [[HYAwesomeTransition alloc] init];
        self.awesometransition.duration = 1.5f;
        self.awesometransition.containerBackgroundView = ({
            UIView *bgView = (UIView *)[[[NSBundle mainBundle] loadNibNamed:@"ContainerBackgroundView" owner:nil options:nil] lastObject];
            bgView;
        });
        // 弹出窗显示2秒后自动消失
        [SVProgressHUD setMinimumDismissTimeInterval:2];
        
    }
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    if (!_strScan) {
        _emailTextField.text = _strScan;
    }
    self.user = [BmobUser getCurrentUser];
    if (self.user) {
        [self haveaUser:self.user.objectId];
        [self.loginButton removeFromSuperview];
        [self initMoreButton];
    }else{
        [self.moreButton removeFromSuperview];
        [self initLoginButton];
    }
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - IBAction
- (void)scanQRCode
{
    if (!_scanViewController) {
        self.scanViewController = [SubLBXScanViewController new];
    }
    [self.navigationController pushViewController:self.scanViewController animated:YES];
}

- (void)initLoginButton
{
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.frame = CGRectMake(SCREEN.width - startMargin - startMargin, startMargin, startMargin, startMargin);
        [_loginButton setTitle:@"登陆" forState:UIControlStateNormal];
        [_loginButton setTitleColor:MILK_WHITE forState:UIControlStateNormal];
        [_loginButton setTitleColor:MILK_GRAY forState:UIControlStateHighlighted];
        [_loginButton setBackgroundColor:MILK_RED];
        [_loginButton addTarget:self action:@selector(loginClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view addSubview:_loginButton];
}

- (void)loginClick
{
    LWLoginViewController *vc = [[LWLoginViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)initMoreButton
{
    if (!_moreButton) {
        _moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _moreButton.frame = CGRectMake(SCREEN.width - startMargin - startMargin, startMargin, startMargin, startMargin);
        UIImage *moreImage = [UIImage imageNamed:@"more"];
        [_moreButton setImage:moreImage forState:UIControlStateNormal];
        [_moreButton addTarget:self action:@selector(moreClick) forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view addSubview:_moreButton];
}

- (void)logoutClick
{
    [BmobUser logout];
    [_moreButton removeFromSuperview];
    [self initLoginButton];
    self.headImageView.image = [UIImage imageNamed:@"defaultHead"];
    _tipLabel.text = @"";
}

- (void)moreClick
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"注销后需要重新登录" message:@"不登陆也可以查询简历" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *logoutAction = [UIAlertAction actionWithTitle:@"注销" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self logoutClick];
    }];
    UIAlertAction *showUserResume = [UIAlertAction actionWithTitle:@"个人简历" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showResume:YES];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:logoutAction];
    [alertController addAction:showUserResume];
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)queryClick:(UIButton *)button
{
    [self.view endEditing:YES];
    [self queryPeopleWithEmail:_emailTextField.text];
}

#pragma mark - 跳转到显示简历界面
- (void)showResume:(BOOL)isShowUserResume
{
    self.user = [BmobUser getCurrentUser];
    if (self.user|| validEmailAtServerHaveResumeBool) {
        LWResumeViewController *vc = [[LWResumeViewController alloc] init];
        vc.queryEmail = _emailTextField.text;
        vc.showUserResume = isShowUserResume;
        vc.transitioningDelegate = self;
        vc.delegate = self;
        
        CGRect headRect = self.headImageView.bounds;
        CGRect startFrame = [self.headImageView convertRect:headRect toView:self.view];
        CGRect finalFrame = CGRectMake((SCREEN.width - 100)*0.5, 25, 100, 100);
        [self.awesometransition registerStartFrame:startFrame finalFrame:finalFrame transitionView:self.headImageView];
        self.headImageView.hidden = YES;
        vc.avatar.image = self.headImageView.image;
        __weak LWResumeViewController *weakVC = vc;
        [self presentViewController:vc animated:YES completion:^{
            weakVC.avatar.image = _headImageView.image;
            weakVC.avatar.hidden = NO;
        }];
    }else if (!validEmailAtServerHaveResumeBool)
    {
        [SVProgressHUD showErrorWithStatus:@"此用户还没有上传简历"];
    }
}

- (void)showResumeWithTap:(UITapGestureRecognizer *)recogizer
{
    [self showResume:NO];
}

#pragma mark - 通过邮箱地址查询用户
- (void)queryPeopleWithEmail:(NSString *)email
{
    if ([LWEvaluateUtil validateEmail:email]) {
        _tipLabel.text = @"合法的邮箱地址";
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
        [bquery whereKey:@"username" equalTo:email];
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (error){
                //进行错误处理
                _tipLabel.text = @"合法的邮箱地址:没有这个用户";
            }else{
                emailAtServerBool = YES;
                for (BmobObject *obj in array) {
                    NSString *objectIdStr = [obj objectId];
                    [self haveaUser:objectIdStr];
                    [self queryResumeWithValidEmail:email withUser:obj];
                }
            }
        }];
    }
    else {
        _tipLabel.text = @"请输入正确的邮箱地址";
    }
}
#pragma mark - 通过邮箱地址查询简历
- (void)queryResumeWithValidEmail:(NSString *)email withUser:(BmobObject *)obj
{
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"Resume"];
    [bquery whereKey:@"email" equalTo:email];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        if (error){
            //进行错误处理
            _tipLabel.text = @"没有这个用户的简历";
        }else{
            validEmailAtServerHaveResumeBool = YES;
            
        }
    }];
}

#pragma mark - transition 从简历界面返回时动画
- (void)resumeViewControllerDidClickedDismissButton:(LWResumeViewController *)viewController
{
    self.awesometransition.snapshotView = [viewController.avatar snapshotViewAfterScreenUpdates:NO];;
    self.awesometransition.finalFrame = [viewController.avatar convertRect:viewController.avatar.bounds toView:viewController.view];
    viewController.avatar.hidden = YES;
    self.headImageView.image = viewController.avatar.image;
    
    [self dismissViewControllerAnimated:YES completion:^{
        self.headImageView.hidden = NO;
    }];
}

#pragma mark - transition

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    self.awesometransition.present = YES;
    return self.awesometransition;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    self.awesometransition.present = NO;
    return self.awesometransition;
}

#pragma mark - 通过用户id查询 用户头像并下载显示
- (void)haveaUser:(NSString *)objectId
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%@.png", objectId]];   // 保存文件的名称
    UIImage *tempImage = [UIImage imageWithContentsOfFile:filePath];
    self.defaultHeadImage = [UIImage imageNamed:@"defaultHead"];
    if (tempImage) {
        self.defaultHeadImage = tempImage;
        self.headImageView.image = self.defaultHeadImage;
    }else
    {
        BmobQuery *bquery = [BmobQuery queryWithClassName:@"Photo"];
        [bquery whereKey:@"filename" equalTo:[NSString stringWithFormat:@"pic_%@.png", objectId]];
        _tipLabel.text = @"合法的邮箱地址:没有这个用户";
        [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
            if (error){
                //进行错误处理
                _tipLabel.text = @"合法的邮箱地址:没有这个用户";
            }else{
                _tipLabel.text = @"合法的邮箱地址:有这个用户";
                if (array.count!=0) {
                    for (BmobObject *obj in array) {
                        BmobFile *file = (BmobFile*)[obj objectForKey:@"filetype"];
                        NSURL *url = [NSURL URLWithString:file.url];
                        NSData *resultData = [NSData dataWithContentsOfURL:url];
                        self.defaultHeadImage = [UIImage imageWithData:resultData];
                        self.headImageView.image = self.defaultHeadImage;
                        [self saveImageToSandbox:self.defaultHeadImage whithImageName:[NSString stringWithFormat:@"pic_%@.png", objectId]];
                    }
                }else
                {
                    self.headImageView.image = [UIImage imageNamed:@"defaultHead"];
                }
            }
        }];
    }
}

#pragma mark - 将图片保存到应用沙盒
- (BOOL)saveImageToSandbox:(UIImage *)image whithImageName:(NSString *)imageNmae
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%@.png", imageNmae]];   // 保存文件的名称
    return [UIImagePNGRepresentation([self scaleToSize:image size:CGSizeMake(100, 100)])writeToFile: filePath atomically:YES];
}

#pragma mark - 将图片缩小到100x100
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark － 通知相关 移除自定义通知中心
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 3DTouch 扫一扫
- (void)gotoTestVc:(NSNotification *)noti {
    NSString *type = noti.userInfo[@"type"];
    if ([type isEqualToString:@"1"]) {        // 测试1
        [self scanQRCode];
    }
}



@end
